package com.loren.tetris.utils;

import com.loren.tetris.data.constant.DataConstant;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;

public class AssistiveUtils {

    /**
     * 获取资源的绝对路径
     */
    public static String getAbsoluteFilePath(String filePath) {
        URL url = AssistiveUtils.class.getProtectionDomain().getCodeSource().getLocation();
        try {
            String tempFilePath = URLDecoder.decode(url.getPath(), "utf-8");
            if (tempFilePath.endsWith(".jar")) {
                File file = new File(tempFilePath);
                return file.getParent() + "\\" + filePath;
            }
            return tempFilePath + filePath;
        } catch (Exception e) {
            throw new RuntimeException("cannot find the resource");
        }
    }

    /**
     * 获取资源图片
     */
    public static BufferedImage getImage(String filePath) {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream(filePath);
        if (inputStream == null) {
            throw new RuntimeException("cannot find the resource");
        }
        try {
            return ImageIO.read(inputStream);
        } catch (IOException e) {
            throw new RuntimeException("cannot find the image resource");
        }
    }

    /**
     * 根据传入的等级，获取下一级所需要的分数
     */
    public static int getNextGameGradeScore(int gameGrade) {
        if (gameGrade < 0) {
            return 0;
        }
        //  50 * (n + 1) * n
        return 50 * (gameGrade + 1 + 1) * (gameGrade + 1);
    }

    /**
     * 根据传入的游戏时间，获取速度睡眠的毫秒数
     */
    public static long getBlockShapeDownSpeed(int minute) {
        if (minute == 0) {
            return DataConstant.GAME_BLOCK_SHAPE_SPEED;
        }
        // y = 1000 - 50 * x     x > 0
        long speed = DataConstant.GAME_BLOCK_SHAPE_SPEED - 50L * minute;
        return Math.max(speed, 100L);
    }

    public static String getFontFamily() {
        return "微软雅黑";
    }
}
